package com.itboye.eweilisten.me.timu;


import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.itboye.eweilisten.R;
import com.itboye.eweilisten.base.BaseActivity;
import com.itboye.eweilisten.me.timu.adapter.XuanCiAdapter;
import com.itboye.eweilisten.model.TiXingBean;
import com.itboye.eweilisten.model.WanXingBean;
import com.itboye.eweilisten.presenter.TiMuPresenter;
import com.itboye.eweilisten.util.loadingutil.MAlert;
import com.itboye.eweilisten.volley.ResultEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 选词填空
 */
public class XuanCiActivity extends BaseActivity implements Observer, OnClickListener {
    TextView tvTitle;
    ImageView back;

    RecyclerView recyclerView;

    ArrayList<String> questions = new ArrayList<String>();//内容
    ArrayList<String> answers = new ArrayList<String>();//答案
    ArrayList<WanXingBean> beans = new ArrayList<WanXingBean>();

    XuanCiAdapter hRecyclerViewAdapter;
    WanXingBean wanXingBean = new WanXingBean(questions, answers);
    TiMuPresenter tiMuPresenter;

    TextView zuoti_title, zuoti_title01;
    TiXingBean bean;

    MediaPlayer player;

    List<TiXingBean.ListInfo> beanList = new ArrayList<>();

    TextView zuoti_zidong;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_wanxing);
        tvTitle.setText("完形填空");
        bean = new TiXingBean();

        recyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);
        tiMuPresenter = new TiMuPresenter(this);
        showProgressDialog("加载中,请稍后",true);
        tiMuPresenter.onXiangQing("171", "9", "itboye");

        back.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.back:
                showPopupWindow(view);
                break;
        }
    }

    /**
     * 退出
     * @param view
     */
    private void showPopupWindow(View view) {
        final View contentView = LayoutInflater.from(XuanCiActivity.this).inflate(
                R.layout.popwindow_back, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.popupwindow_anim_style);
        TextView cancel, sure;
        cancel = (TextView) contentView.findViewById(R.id.cancel);
        sure = (TextView) contentView.findViewById(R.id.sure);
        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        sure.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                popupWindow.dismiss();
            }
        });
        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });



        // 设置好参数之后再show
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }
    /**
     * 开始
     */
    private void kaishiWindow() {
        final View contentView = LayoutInflater.from(XuanCiActivity.this).inflate(
                R.layout.popwindow_start, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        popupWindow.setAnimationStyle(R.style.popupwindow_anim_style);
        TextView cancel, sure;
        cancel = (TextView) contentView.findViewById(R.id.cancel);
        sure = (TextView) contentView.findViewById(R.id.sure);
        cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                popupWindow.dismiss();
            }
        });
        sure.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();

                CountDownTimer cdt = new CountDownTimer(Integer.parseInt(bean.getTime_limit() + "") * 60 * 1000, 1000) {
                    //                    CountDownTimer cdt = new CountDownTimer(5000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        zuoti_zidong.setText("自动提交：" + millisUntilFinished / 1000 + "″");
                    }
                    @Override
                    public void onFinish() {

                    }
                };
                cdt.start();
                new TestTask().execute();
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.i("mengdd", "onTouch : ");
                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        // 设置好参数之后再show
        popupWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);
    }
    class TestTask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... strings) {
            for (int i = 0; i < beanList.size(); i++) {

                if (player == null) {
                    player = MediaPlayer.create(XuanCiActivity.this, Uri.parse(beanList.get(i).getAudio_path()));
                    player.start();

                } else {
                    if (player.isPlaying()) {

                    } else {
                        player = MediaPlayer.create(XuanCiActivity.this, Uri.parse(beanList.get(i).getAudio_path()));
                        player.start();
                    }
                }
//                while (true) {
//                    if (player.isPlaying()) {
//
//                    } else {
//                        break;
//                    }
//                }
            }
            return null;
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }

    @Override
    public void update(Observable observable, Object o) {
        ResultEntity entity = handlerError(o);
        if (entity != null) {
            if (entity.getEventType() == tiMuPresenter.zuoti_xq_success) {
                bean = (TiXingBean) entity.getData();

                zuoti_title.setText(bean.getName());
                zuoti_title01.setText(bean.getParent_name());

                List<TiXingBean.ListInfo> list = new ArrayList<TiXingBean.ListInfo>();
                list.addAll(bean.getList());

                beanList = list;

                Log.d("tixingcuowu", "" + list);
                for (int i = 0; i < list.size(); i++) {
                    questions = new ArrayList<>();
                    answers = new ArrayList<>();
                    //内容
                    for (int j = 0; j < list.get(i).getContent().get(0).size(); j++) {
                        if ("con".equals(list.get(i).getContent().get(0).get(j)[0] + "")) {
                            //___
                            questions.add("_");
                        } else if ("str".equals(list.get(i).getContent().get(0).get(j)[0] + "")) {

                            //有文字
                            questions.add(list.get(i).getContent().get(0).get(j)[1] + "");
                        }

                    }
                    //答案
                    for (int j = 0; j < list.get(i).getAnswer().size(); j++) {
                        if ("str".equals(list.get(i).getAnswer().get(j)[1] + "")) {
                            answers.add(list.get(i).getAnswer().get(j)[0] + "");
                        }
                    }

                    wanXingBean = new WanXingBean(questions, answers);
                    beans.add(wanXingBean);
                }
                recyclerView.setLayoutManager(new LinearLayoutManager(this));
                hRecyclerViewAdapter = new XuanCiAdapter(XuanCiActivity.this, beans);
                recyclerView.setAdapter(hRecyclerViewAdapter);


//                new ClockTask().execute(bean);



            } else if (entity.getEventType() == tiMuPresenter.zuoti_xq_fail) {
                MAlert.alert(entity.getData(), Gravity.TOP);
            }
        }

        try {
            closeProgressDialog();
            kaishiWindow();
        }catch (Exception n){
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player.isPlaying()) {
            player.stop();
        }
        player.release();
    }
}
